<script setup lang="tsx">
import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { addFullName, listToTree } from '@vben/utils';

import {
  Alert,
  Button,
  Checkbox,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Spin,
} from 'ant-design-vue';

import {
  addCategory,
  getCategoryByAi,
  getCategoryList,
} from '#/api/interview/category';

const emit = defineEmits<{ reload: [] }>();
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;

const form = ref({
  parentId: undefined,
  key: '',
});

const [AiCategoryModal, modalApi] = useVbenModal({
  onOpenChange: (isOpen: boolean) => {
    if (isOpen) {
      resetForm();
      fetchParentCategories();
    }
  },
  onConfirm: handleSubmit,
});

const treeData = ref<any[]>([]);
const aiSuggestions = ref<string[]>([]);
const selectedSuggestions = ref<string[]>([]);
const existingChildren = ref<string[]>([]);
const loading = ref(false);
const aiLoading = ref(false);
const formRef = ref();

// 获取所有分类的扁平化列表，用于查找父级分类名称
const flatCategoryList = computed(() => {
  const result: any[] = [];

  function flattenCategories(categories: any[], prefix = '') {
    categories.forEach((category) => {
      result.push({
        categoryId: category.categoryId,
        categoryName: category.categoryName,
        fullName: prefix
          ? `${prefix} / ${category.categoryName}`
          : category.categoryName,
      });

      if (category.children && category.children.length > 0) {
        flattenCategories(
          category.children,
          prefix
            ? `${prefix} / ${category.categoryName}`
            : category.categoryName,
        );
      }
    });
  }

  if (treeData.value && treeData.value.length > 0) {
    // 跳过根节点"无父级分类"
    treeData.value.forEach((item) => {
      if (item.children && item.children.length > 0) {
        flattenCategories(item.children);
      }
    });
  }

  return result;
});

// 获取父级分类选项
async function fetchParentCategories() {
  try {
    const res = await getCategoryList({ status: '0', parentId: 0 });
    const tree = listToTree(res.rows, {
      id: 'categoryId',
      pid: 'parentId',
      children: 'children',
    });
    addFullName(tree, 'categoryName', ' / ');

    treeData.value = [
      {
        categoryId: 0,
        categoryName: '无父级分类',
        children: tree,
      },
    ];
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
}

// 获取父级分类下的已有子分类
async function fetchExistingChildren(parentId?: number) {
  if (parentId === undefined || parentId === null) {
    existingChildren.value = [];
    return;
  }

  try {
    const res = await getCategoryList({ parentId });
    existingChildren.value = res.rows.map((item: any) => item.categoryName);
  } catch (error) {
    console.error('获取已有子分类失败:', error);
    existingChildren.value = [];
  }
}

// 监听父级分类的变化
watch(
  () => form.value.parentId,
  (newParentId) => {
    fetchExistingChildren(newParentId);

    // 清空AI建议分类
    aiSuggestions.value = [];
    selectedSuggestions.value = [];

    // 自动填充提示词
    if (newParentId !== undefined && newParentId !== null) {
      let parentName = '';

      if (newParentId === 0) {
        parentName = '无父级分类';
      } else {
        const parentCategory = flatCategoryList.value.find(
          (item: any) => item.categoryId === newParentId,
        );
        if (parentCategory) {
          parentName = parentCategory.fullName || parentCategory.categoryName;
        }
      }

      // 设置固定的提示词并拼接父级分类名称
      form.value.key = `这是关于"${parentName}"的面试题分类，除此之外还有哪些相关分类？`;
    } else {
      form.value.key = '';
    }
  },
);

// 通过AI获取分类建议
async function getCategoriesByAi() {
  if (!form.value.parentId && form.value.parentId !== 0) {
    Modal.warning({
      title: '提示',
      content: '请选择父级分类',
    });
    return;
  }

  if (!form.value.key.trim()) {
    Modal.warning({
      title: '提示',
      content: '请输入提示词',
    });
    return;
  }

  try {
    aiLoading.value = true;
    const res = await getCategoryByAi({
      prompt: form.value.key,
      parentId: form.value.parentId,
    });

    if (res) {
      aiSuggestions.value = res;
      selectedSuggestions.value = [];
    } else {
      aiSuggestions.value = [];
      selectedSuggestions.value = [];
      Modal.info({
        title: '提示',
        content: '暂无相关分类建议',
      });
    }
  } catch (error) {
    console.error('获取AI分类建议失败:', error);
    Modal.error({
      title: '错误',
      content: '获取AI分类建议失败',
    });
  } finally {
    aiLoading.value = false;
  }
}

// 提交选中的分类
async function handleSubmit() {
  if (selectedSuggestions.value.length === 0) {
    Modal.warning({
      title: '提示',
      content: '请至少选择一个分类',
    });
    return;
  }

  // 检查是否有重复的分类名称
  const duplicateNames = selectedSuggestions.value.filter((suggestion) =>
    existingChildren.value.includes(suggestion),
  );

  if (duplicateNames.length > 0) {
    Modal.confirm({
      title: '提示',
      content: `以下分类已存在：${duplicateNames.join('、')}，是否仍要添加？`,
      onOk: () => {
        submitCategories();
      },
    });
    return;
  }

  await submitCategories();
}

// 实际提交分类的函数
async function submitCategories() {
  try {
    loading.value = true;
    const parentId = form.value.parentId || 0;

    // 循环添加选中的分类
    for (const categoryName of selectedSuggestions.value) {
      await addCategory({
        categoryDescription: categoryName,
        categoryName,
        parentId,
      });
    }

    Modal.success({
      title: '成功',
      content: `成功添加 ${selectedSuggestions.value.length} 个分类`,
      onOk() {
        modalApi.close();
        emit('reload');
      },
    });
  } catch (error) {
    console.error('添加分类失败:', error);
    Modal.error({
      title: '错误',
      content: '添加分类失败',
    });
  } finally {
    loading.value = false;
  }
}

// 重置表单
function resetForm() {
  form.value = {
    parentId: undefined,
    key: '',
  };
  aiSuggestions.value = [];
  selectedSuggestions.value = [];
  existingChildren.value = []; // 重置已有子分类
}

defineExpose({
  modalApi,
});
</script>

<template>
  <AiCategoryModal :destroy-on-close="true" title="AI生成分类">
    <Spin :spinning="loading || aiLoading">
      <Form ref="formRef" :model="form" layout="vertical">
        <FormItem
          label="父级分类"
          name="parentId"
          :rules="[{ required: true, message: '请选择父级分类' }]"
        >
          <Select
            v-model:value="form.parentId"
            placeholder="请选择父级分类"
            show-search
            option-filter-prop="label"
          >
            <template v-for="item in treeData" :key="item.categoryId">
              <Select.OptGroup
                v-if="item.children && item.children.length > 0"
                :label="item.categoryName"
              >
                <Select.Option
                  v-for="child in item.children"
                  :key="child.categoryId"
                  :value="child.categoryId"
                >
                  {{ child.categoryName }}
                </Select.Option>
              </Select.OptGroup>
              <Select.Option v-else :value="item.categoryId">
                {{ item.categoryName }}
              </Select.Option>
            </template>
          </Select>
        </FormItem>

        <FormItem
          label="提示词"
          name="key"
          :rules="[{ required: true, message: '请输入提示词' }]"
        >
          <Input
            v-model:value="form.key"
            placeholder="请输入提示词，如：Java相关的面试题分类"
          />
        </FormItem>

        <FormItem>
          <Button
            type="primary"
            @click="getCategoriesByAi"
            :loading="aiLoading"
          >
            获取AI建议
          </Button>
        </FormItem>

        <FormItem v-if="aiSuggestions.length > 0" label="AI建议分类">
          <Alert
            message="以下是由AI根据提示词生成的相关分类建议，请选择需要添加的分类"
            type="info"
            show-icon
            style="margin-bottom: 12px"
          />
          <CheckboxGroup
            v-model:value="selectedSuggestions"
            :options="aiSuggestions"
          />
        </FormItem>

        <FormItem v-if="existingChildren.length > 0" label="已有子分类">
          <Alert
            message="以下是在当前父级分类下已存在的子分类，避免重复添加"
            type="warning"
            show-icon
            style="margin-bottom: 12px"
          />
          <div style="display: flex; flex-wrap: wrap; gap: 8px">
            <span
              v-for="(child, index) in existingChildren"
              :key="index"
              style="
                background-color: #f0f0f0;
                padding: 4px 8px;
                border-radius: 4px;
              "
            >
              {{ child }}
            </span>
          </div>
        </FormItem>
      </Form>

      <template #footer>
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
            :disabled="selectedSuggestions.length === 0"
          >
            添加选中分类
          </Button>
        </Space>
      </template>
    </Spin>
  </AiCategoryModal>
</template>
